package com.waves.netty.io;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 基于阻塞IO的数据excel导出
 */
public class IOExcelExport {

    public static void main(String[] args) {
        // 1. 准备数据
        List<String[]> data = prepareData();

        // 2. 创建 Excel 工作簿
        Workbook workbook = new XSSFWorkbook(); // 使用 XSSFWorkbook 创建 .xlsx 格式
        Sheet sheet = workbook.createSheet("Sheet1");

        // 3. 创建表头
        String[] headers = {"姓名", "年龄", "性别",
                "地址", "城市", "省份", "邮政编码", "国家"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);

            // 设置样式 (可选)
            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            headerStyle.setFont(font);
            cell.setCellStyle(headerStyle);
        }

        // 4. 写入数据
        int rowNum = 1;
        for (String[] rowData : data) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 0; i < rowData.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(rowData[i]);
            }
        }

        // 5. 自动调整列宽 (可选)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 6. 导出 Excel 文件
        long startTime = System.currentTimeMillis();
        String filePath = "阻塞IO.xlsx";
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
            System.out.println("Excel file exported successfully to " + filePath);
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
        } finally {
            try {
                workbook.close(); // 关闭 workbook 释放资源
            } catch (IOException e) {
                System.err.println("Error closing workbook: " + e.getMessage());
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("程序运行时间：" + (endTime - startTime) + " 毫秒");
    }

    // 准备测试数据
    private static List<String[]> prepareData() {
        List<String[]> data = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            data.add(new String[]{"张"+i, String.valueOf(i), "男",
            "苏州","China","新区","000000","江苏省"});
        }
        return data;
    }
}